<template>
  <div class="mapchart">

  </div>
</template>

<script lang="ts">
import { computed, defineComponent, inject, nextTick, onMounted, PropType, ref, Ref, watch } from 'vue'
import { upperFirst } from 'lodash'
import tinycolor from 'tinycolor2'
import Chartist, {
  IChartistLineChart,
  IChartistBarChart,
  IChartistPieChart,
  ILineChartOptions,
  IBarChartOptions,
  IPieChartOptions,
} from 'chartist'
import { ChartData, ChartType, antvChartData } from '@/types/slides'
import { useMainStore, useSlidesStore } from '@/store'
import { storeToRefs } from 'pinia'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'

import 'chartist/dist/scss/chartist.scss'
import { Scene, PolygonLayer, LineLayer, PointLayer, EarthLayer, Popup } from '@antv/l7'
import { Mapbox, Earth } from '@antv/l7-maps'
import { createRandomCode } from '@/utils/common'

export default defineComponent({
  name: 'chart',
  props: {
    width: {
      type: Number,
      required: true,
    },
    height: {
      type: Number,
      required: true,
    },
    type: {
      type: String as PropType<ChartType>,
      required: true,
    },
    data: {
      type: Object as PropType<antvChartData>,
      required: true,
    },
    options: {
      type: Object as PropType<ILineChartOptions & IBarChartOptions & IPieChartOptions>,
    },
    themeColor: {
      type: Array as PropType<string[]>,
      required: true,
    },
    // legends: {
    //   type: Array as PropType<string[]>,
    //   required: true,
    // },
    gridColor: {
      type: String,
    },
    legend: {
      type: String as PropType<'' | 'top' | 'bottom'>,
    },
    id: {
      type: String,
    }
  },
  setup(props) {
    const slidesStore = useSlidesStore()
    const chartRef = ref<HTMLElement>()
    const slideScale: Ref<number> = inject('slideScale') || ref(1)
    const mainStore = useMainStore()
    const { handleElement, handleElementId } = storeToRefs(mainStore)
    const { addHistorySnapshot } = useHistorySnapshot()
    // const { DataView } = DataSet;
    // let chart: IChartistLineChart | IChartistBarChart | IChartistPieChart | undefined
    let charts: any
    let scene: any
    const chartHeight = computed(() => {
      // if (props.legend) return props.height - 20
      return props.height
    })

    // const getDataAndOptions = () => {
    //   const propsOptopns = props.options || {}
    //   const options = {
    //     ...propsOptopns,
    //     width: props.width * slideScale.value,
    //     height: chartHeight.value * slideScale.value,
    //   }
    //   const data = props.type === 'pie' ? { ...props.data, series: props.data.series[0] } : props.data
    //   return { data, options }
    // }

    watch(() => chartHeight.value,
      (val) => {
        // charts.changeSize(props.width * slideScale.value, chartHeight.value * slideScale.value)
      })
    const mapList = [
      {
        type: '2dmap1',
        center: [ 116.368652, 39.93866 ],
        zoom: 10.07,
        style: 'blank',
        url1: 'https://gw.alipayobjects.com/os/bmw-prod/d6da7ac1-8b4f-4a55-93ea-e81aa08f0cf3.json',
        url2: 'https://gw.alipayobjects.com/os/bmw-prod/c4a6aa9d-8923-4193-a695-455fd8f6638c.json',
        colorlist: [
                  'rgb(239,243,255)',
                  'rgb(189,215,231)',
                  'rgb(107,174,214)',
                  'rgb(49,130,189)',
                  'rgb(8,81,156)'
                ]
      },
      {
        type: '2dmap2',
        center: [ 116.368652, 39.93866 ],
        zoom: 10.07,
        style: 'blank',
        url1: 'https://gw.alipayobjects.com/os/bmw-prod/707cd4be-8ffe-4778-b863-3335eefd5fd5.json',
        url2: 'https://gw.alipayobjects.com/os/bmw-prod/d09a3567-8c0e-4711-b8b8-cd82e8870e4b.json',
        colorlist: ['#fee5d9', '#fcae91', '#fb6a4a', '#de2d26', '#a50f15' ]
      },
      {
        center: [ -96, 37.8 ],
        zoom: 3,
        style: 'light',
        url1: 'https://gw.alipayobjects.com/os/basement_prod/d36ad90e-3902-4742-b8a2-d93f7e5dafa2.json',
        colorlist: ['rgb(255,255,217)', 'rgb(237,248,177)', 'rgb(199,233,180)', 'rgb(127,205,187)', 'rgb(65,182,196)', 'rgb(29,145,192)', 'rgb(34,94,168)', 'rgb(12,44,132)' ]
      },
      {
        center: [ 116.368652, 39.93866 ],
        zoom: 8,
        style: 'light',
        url1: 'https://gw.alipayobjects.com/os/basement_prod/1d27c363-af3a-469e-ab5b-7a7e1ce4f311.json',
        colorlist: [
            '#1A4397',
            '#2555B7',
            '#3165D1',
            '#467BE8',
            '#6296FE',
            '#7EA6F9',
            '#98B7F7',
            '#BDD0F8',
            '#DDE6F7',
            '#F2F5FC'
          ]
      }
    ]
    const renderChart = () => {
      const currentElement = document.querySelector('#editable-element-'+props.id) as HTMLElement
      const parent = currentElement.querySelector('.mapchart') as HTMLElement
      const html = document.createElement('div')
      const id = createRandomCode(3)
      html.setAttribute('id',id)
      html.setAttribute('class', 'chart')
      
      html.style.width = props.width + 'px'
      html.style.height = chartHeight.value+'px'
      parent.appendChild(html)

      let mapdata: any = {
        url1: 'https://gw.alipayobjects.com/os/bmw-prod/d6da7ac1-8b4f-4a55-93ea-e81aa08f0cf3.json',
        url2: 'https://gw.alipayobjects.com/os/bmw-prod/c4a6aa9d-8923-4193-a695-455fd8f6638c.json',
        colorlist: [
                  'rgb(239,243,255)',
                  'rgb(189,215,231)',
                  'rgb(107,174,214)',
                  'rgb(49,130,189)',
                  'rgb(8,81,156)'
                ]
      }
      if(props.data.type.type == '2DMAP1'){
        mapdata = mapList[0]
      }
      if(props.data.type.type == '2DMAP2'){
        mapdata = mapList[1]
      }
      if(props.data.type.type == '2DMAP3'){
        mapdata = mapList[2]
      }
      if(props.data.type.type == '2DMAP4'){
        mapdata = mapList[3]
      }
      scene = new Scene({
        id: id,
        map: new Mapbox({
          pitch: 0,
          style: mapdata.style,
          center: mapdata.center,
          zoom: mapdata.zoom
        })
      });
      if(props.data.type.type == '2DMAP1' || props.data.type.type == '2DMAP2'){
        scene.on('loaded', () => {
        fetch(mapdata.url1)
          .then(res => res.json())
          .then(data => {
            const chinaPolygonLayer = new PolygonLayer({
              autoFit: true
            })
              .source(data)
              .color(
                'name',
                 mapdata.colorlist
              )
              .shape('fill')
              .style({
                opacity: 1
              });
              //  图层边界
            const layer2 = new LineLayer({
              zIndex: 2
            })
              .source(data)
              .color('rgb(93,112,146)')
              .size(0.6)
              .style({
                opacity: 1
              });

            scene.addLayer(chinaPolygonLayer);
            scene.addLayer(layer2);
          });
        fetch(mapdata.url2).then(res => res.json())
          .then(data => {
            const labelLayer = new PointLayer({
              zIndex: 5
            })
              .source(data, {
                parser: {
                  type: 'json',
                  coordinates: 'center'
                }
              })
              .color('#fff')
              .shape('name', 'text')
              .size(12)
              .style({
                opacity: 1,
                stroke: '#fff',
                strokeWidth: 0,
                padding: [ 5, 5 ],
                textAllowOverlap: false
              });

            scene.addLayer(labelLayer);
          });
      });
      }
      if(props.data.type.type == '2DMAP3'){
        scene.on('loaded', () => {
          fetch(
            mapdata.url1
          )
            .then(res => res.json())
            .then(data => {
              const color = mapdata.colorlist;
              const layer = new PolygonLayer({})
                .source(data)
                .scale('density', {
                  type: 'quantize'
                })
                .color(
                  'density', color
                )
                .shape('fill')
                .active(true)
                .style({
                  opacity: 1.0
                });
              const layer2 = new LineLayer({
                zIndex: 2
              })
                .source(data)
                .color('#fff')
                .active(true)
                .size(1)
                .style({
                  lineType: 'dash',
                  dashArray: [ 2, 2 ],
                  opacity: 1
                });
              scene.addLayer(layer);
              scene.addLayer(layer2);

              layer.on('mousemove', e => {
                const popup = new Popup({
                  offsets: [ 0, 0 ],
                  closeButton: false
                })
                  .setLnglat(e.lngLat)
                  .setHTML(`<span>${e.feature.properties.name}: ${e.feature.properties.density}</span>`);
                scene.addPopup(popup);
              });
            });
        });
      }
      if(props.data.type.type == '2DMAP4'){
        scene.on('loaded', () => {
          fetch(
            mapdata.url1
          )
            .then(res => res.json())
            .then(data => {
              const layer = new PolygonLayer({})
                .source(data)
                .color(
                  'unit_price',
                  mapdata.colorlist.reverse()
                )
                .shape('fill')
                .active(true)
                .style({
                  opacity: 1
                });
              const layer2 = new LineLayer({
                zIndex: 2
              })
                .source(data)
                .color('#fff')
                .size(0.8)
                .style({
                  opacity: 1
                });

              scene.addLayer(layer);
              scene.addLayer(layer2);
            });
        });
      }
    }

    const updateChart = () => {
      if (!charts) {
        return
      }
      if (props.id != handleElement.value?.id) {
        return
      }
      // const { data, options } = getDataAndOptions()

      if (handleElement.value?.type == 'chart' && handleElement.value?.data) {
        let s = handleElement.value?.data.type.s;
        let x = handleElement.value?.data.type.x;
        let y = handleElement.value?.data.type.y;
        let data = handleElement.value?.data.data;
        charts.changeData(data);

        console.log("updateChart", s, x, y)

        // renderChart()
      }
      // chart.update(data, options)
    }

    watch([
      () => props.width,
      () => props.height,
      () => props.data,
      slideScale,
    ], updateChart)

    onMounted(renderChart)

    const themeColors = computed(() => {
      let colors: string[] = []
      if (props.themeColor.length >= 10) colors = props.themeColor
      else if (props.themeColor.length === 1) colors = tinycolor(props.themeColor[0]).analogous(10).map(color => color.toHexString())
      else {
        const len = props.themeColor.length
        const supplement = tinycolor(props.themeColor[len - 1]).analogous(10 + 1 - len).map(color => color.toHexString())
        colors = [...props.themeColor.slice(0, len - 1), ...supplement]
      }

      return colors
    })

    // 更新主题配色：
    // 如果当前所设置的主题色数小于10，剩余部分获取最后一个主题色的相近颜色作为配色
    const updateTheme = () => {
      if (!chartRef.value) return

      for (let i = 0; i < 10; i++) {
        chartRef.value.style.setProperty(`--theme-color-${i + 1}`, themeColors.value[i])
      }
      
      const props: any = {
        themeColor: themeColors,
      }
      // slidesStore.updateElement({ id: handleElementId.value, props })
      addHistorySnapshot()
    }

    watch(themeColors, updateTheme)
    // onMounted(updateTheme)

    // 更新网格颜色，包括坐标的文字部分
    const updateGridColor = () => {
      if (!chartRef.value) return
      if (props.gridColor) chartRef.value.style.setProperty(`--grid-color`, props.gridColor)
    }

    watch(() => props.gridColor, updateGridColor)
    onMounted(updateGridColor)

    return {
      chartHeight,
      themeColors,
      slideScale,
      chartRef,
      DataView,
      handleElement,
      handleElementId,
    }
  },
})
</script>

<style lang="scss" scoped>
.chart {
  display: flex;
}

.chart-content {
  transform-origin: 0 0;
}
</style>

<style lang="scss">
.l7-ctrl-logo {
  display: none;
}
.chart-content {
  $ct-series-names: (a, b, c, d, e, f, g, h, i, j);

  --theme-color-1: #666;
  --theme-color-2: #666;
  --theme-color-3: #666;
  --theme-color-4: #666;
  --theme-color-5: #666;
  --theme-color-6: #666;
  --theme-color-7: #666;
  --theme-color-8: #666;
  --theme-color-9: #666;
  --theme-color-10: #666;

  @for $i from 1 to length($ct-series-names) {
    $color: var(--theme-color-#{$i});

    .ct-series-#{nth($ct-series-names, $i)} .ct-line {
      stroke: $color;
    }

    .ct-series-#{nth($ct-series-names, $i)} .ct-point {
      stroke: $color;
    }

    .ct-series-#{nth($ct-series-names, $i)} .ct-area {
      fill: $color;
    }

    .ct-series-#{nth($ct-series-names, $i)} .ct-bar {
      stroke: $color;
    }

    .ct-series-#{nth($ct-series-names, $i)} .ct-slice-pie {
      fill: $color;
    }

    .ct-series-#{nth($ct-series-names, $i)} .ct-slice-donut {
      stroke: $color;
    }
  }

  --grid-color: rgba(0, 0, 0, 0.4);

  .ct-grid {
    stroke: var(--grid-color);
  }

  .ct-label {
    fill: var(--grid-color);
    color: var(--grid-color);
  }
}

.legends {
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
}

.legend {
  display: flex;
  align-items: center;

  &+.legend {
    margin-left: 10px;
  }

  .block {
    width: 10px;
    height: 10px;
    margin-right: 5px;
  }
}
</style>